import { NextRequest, NextResponse } from 'next/server';
import { getToken } from 'next-auth/jwt';
import prisma from '@/lib/auth/prisma';

// 获取文档列表
export async function GET(req: NextRequest) {
  try {
    const token = await getToken({ req });
    if (!token?.id) {
      return NextResponse.json({ error: '未授权访问' }, { status: 401 });
    }

    const documents = await prisma.document.findMany({
      where: {
        authorId: token.id,
      },
      orderBy: {
        updatedAt: 'desc',
      },
    });

    return NextResponse.json(documents);
  } catch (error) {
    console.error('获取文档列表失败:', error);
    return NextResponse.json(
      { error: '获取文档列表失败' },
      { status: 500 }
    );
  }
}

// 创建新文档
export async function POST(req: NextRequest) {
  try {
    const token = await getToken({ req });
    if (!token?.id) {
      return NextResponse.json({ error: '未授权访问' }, { status: 401 });
    }

    const { title, content } = await req.json();

    if (!title || !content) {
      return NextResponse.json(
        { error: '标题和内容不能为空' },
        { status: 400 }
      );
    }

    const document = await prisma.document.create({
      data: {
        title,
        content,
        authorId: token.id,
      },
    });

    return NextResponse.json(document, { status: 201 });
  } catch (error) {
    console.error('创建文档失败:', error);
    return NextResponse.json(
      { error: '创建文档失败' },
      { status: 500 }
    );
  }
}